<template>
  <div class="inventory-container">
    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" class="inventory-tabs">
      <el-tab-pane label="商品信息管理" name="products">
        <div class="tab-content">
          <div class="tab-header">
            <h2 class="tab-title">商品信息管理</h2>
            <el-button type="primary" @click="showAddModal = true">
              新增商品
            </el-button>
          </div>

          <!-- 查询条件 -->
          <el-card class="search-card">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-input v-model="searchForm.productName" placeholder="商品名称" clearable />
              </el-col>
              <el-col :span="6">
                <el-select v-model="searchForm.category" placeholder="商品分类" clearable style="width: 100%">
                  <el-option label="狗粮" value="狗粮" />
                  <el-option label="猫粮" value="猫粮" />
                  <el-option label="玩具" value="玩具" />
                  <el-option label="用品" value="用品" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-input v-model="searchForm.brand" placeholder="品牌" clearable />
              </el-col>
              <el-col :span="6">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-input v-model="searchForm.minStock" placeholder="最小库存" type="number" />
                  </el-col>
                  <el-col :span="12">
                    <el-input v-model="searchForm.maxStock" placeholder="最大库存" type="number" />
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-card>

          <!-- 库存预警 -->
          <el-alert title="库存预警" :description="`有 ${lowStockCount} 种商品库存不足，需要及时补货`" type="warning" :closable="false"
            show-icon class="stock-alert" v-if="lowStockCount > 0" />

          <!-- 商品列表 -->
          <el-card class="table-card">
            <el-table :data="products" style="width: 100%">
              <el-table-column prop="name" label="商品名称" width="150" />
              <el-table-column prop="category" label="分类" width="100" />
              <el-table-column prop="brand" label="品牌" width="100" />
              <el-table-column prop="stock" label="库存数量" width="120" />
              <el-table-column prop="salePrice" label="销售价" width="120" />
              <el-table-column prop="expiryDate" label="保质期" width="120" />
              <el-table-column label="操作" width="300">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                    删除
                  </el-button>
                  <el-button type="success" size="small" @click="openOrderModal(scope.row)">
                    下单
                  </el-button>
                  <el-button type="warning" size="small" @click="openRestockModal(scope.row)">
                    进货
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 16px; text-align: right;">
              <el-pagination background layout="total, prev, pager, next, sizes, jumper" :total="productTotal"
                :current-page="productCurrentPage" :page-size="productPageSize" :page-sizes="[5, 10, 20, 50]"
                @size-change="handleProductSizeChange" @current-change="handleProductPageChange" />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="进货管理" name="purchase">
        <div class="tab-content">
          <div class="tab-header">
            <h2 class="tab-title">进货管理</h2>
          </div>

          <!-- 查询条件 -->
          <el-card class="search-card">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-date-picker v-model="purchaseSearchForm.startDate" type="date" placeholder="开始日期"
                  style="width: 100%" />
              </el-col>
              <el-col :span="8">
                <el-date-picker v-model="purchaseSearchForm.endDate" type="date" placeholder="结束日期"
                  style="width: 100%" />
              </el-col>
            </el-row>
            <div class="search-buttons">
              <el-button type="primary" @click="handlePurchaseSearch">查询</el-button>
              <el-button @click="handlePurchaseReset">重置</el-button>
            </div>
          </el-card>

          <!-- 进货记录列表 -->
          <el-card class="table-card">
            <el-table :data="purchaseRecords" style="width: 100%">
              <el-table-column prop="supplierName" label="供应商" width="200" />
              <el-table-column label="进货日期" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.purchaseDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" width="150" />
              <el-table-column prop="quantity" label="进货数量" width="120" />
              <el-table-column label="进货单价" width="120">
                <template #default="scope">
                  <span v-if="typeof scope.row.unitPrice === 'number'">¥{{ scope.row.unitPrice.toFixed(2) }}</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column label="总金额" width="120">
                <template #default="scope">
                  <span v-if="typeof scope.row.totalAmount === 'number'">¥{{ scope.row.totalAmount.toFixed(2) }}</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="handleEditPurchase(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeletePurchase(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 16px; text-align: right;">
              <el-pagination background layout="total, prev, pager, next, sizes, jumper" :total="purchaseTotal"
                :current-page="purchaseCurrentPage" :page-size="purchasePageSize" :page-sizes="[5, 10, 20, 50]"
                @size-change="handlePurchaseSizeChange" @current-change="handlePurchasePageChange" />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 新增：供应商管理tab -->
      <el-tab-pane label="供应商管理" name="suppliers">
        <div class="tab-content">
          <div class="tab-header">
            <h2 class="tab-title">供应商管理</h2>
            <el-button type="primary" @click="showAddSupplierModal = true">
              新增供应商
            </el-button>
          </div>
          <!-- 查询条件 -->
          <el-card class="search-card">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input v-model="supplierSearchForm.supplierName" placeholder="供应商名称" clearable />
              </el-col>
              <el-col :span="8">
                <el-input v-model="supplierSearchForm.contact" placeholder="联系方式" clearable />
              </el-col>
              <el-col :span="8">
                <el-input v-model="supplierSearchForm.address" placeholder="地址" clearable />
              </el-col>
            </el-row>
            <div class="search-buttons">
              <el-button type="primary" @click="handleSupplierSearch">查询</el-button>
              <el-button @click="handleSupplierReset">重置</el-button>
            </div>
          </el-card>
          <!-- 供应商列表 -->
          <el-card class="table-card">
            <el-table :data="suppliers" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="供应商名称" width="180" />
              <el-table-column prop="contact" label="联系方式" width="150" />
              <el-table-column prop="address" label="地址" />
              <el-table-column prop="status" label="状态" width="100" />
              <el-table-column label="操作" width="160">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="handleEditSupplier(scope.row)">编辑</el-button>
                  <el-button type="danger" size="small" @click="handleDeleteSupplier(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 16px; text-align: right;">
              <el-pagination background layout="total, prev, pager, next, sizes, jumper" :total="supplierTotal"
                :current-page="supplierCurrentPage" :page-size="supplierPageSize" :page-sizes="[5, 10, 20, 50]"
                @size-change="handleSupplierSizeChange" @current-change="handleSupplierPageChange" />
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增/编辑商品模态框 -->
    <el-dialog v-model="showAddModal" :title="editingProduct ? '编辑商品信息' : '新增商品信息'" width="60%">
      <el-form :model="productForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" required>
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" required>
              <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="狗粮" value="狗粮" />
                <el-option label="猫粮" value="猫粮" />
                <el-option label="玩具" value="玩具" />
                <el-option label="用品" value="用品" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-input v-model="productForm.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格">
              <el-input v-model="productForm.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进货价(¥)" required>
              <el-input-number v-model="productForm.purchasePrice" :precision="2" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价(¥)" required>
              <el-input-number v-model="productForm.salePrice" :precision="2" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保质期">
              <el-date-picker v-model="productForm.expiryDate" type="date" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddModal = false">取消</el-button>
          <el-button type="primary" @click="handleSaveProduct">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑进货记录模态框 -->
    <el-dialog v-model="showAddPurchaseModal" :title="editingPurchase ? '编辑进货记录' : '新增进货记录'" width="60%">
      <el-form :model="purchaseForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商名称" required>
              <el-select v-model="purchaseForm.supplierName" placeholder="请选择供应商" style="width: 100%">
                <el-option v-for="sup in suppliers" :key="sup.id" :label="sup.name" :value="sup.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商联系方式">
              <el-input v-model="purchaseForm.supplierContact" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进货日期" required>
              <el-date-picker v-model="purchaseForm.purchaseDate" type="date" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" required>
              <el-select v-model="purchaseForm.productName" placeholder="请选择商品" style="width: 100%">
                <el-option v-for="product in products" :key="product.id" :label="product.name" :value="product.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进货数量" required>
              <el-input-number v-model="purchaseForm.quantity" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进货单价(¥)" required>
              <el-input-number v-model="purchaseForm.unitPrice" :precision="2" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddPurchaseModal = false">取消</el-button>
          <el-button type="primary" @click="handleSavePurchase">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑供应商模态框 -->
    <el-dialog v-model="showAddSupplierModal" :title="editingSupplier ? '编辑供应商' : '新增供应商'" width="50%">
      <el-form :model="supplierForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商名称" required>
              <el-input v-model="supplierForm.name" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" required>
              <el-input v-model="supplierForm.contact" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地址" required>
              <el-input v-model="supplierForm.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddSupplierModal = false">取消</el-button>
          <el-button type="primary" @click="handleSaveSupplier">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 下单弹窗 -->
    <el-dialog v-model="showOrderModal" title="商品下单" width="40%">
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="orderForm.productName" disabled />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="orderForm.brand" disabled />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="orderForm.salePrice" disabled />
        </el-form-item>
        <el-form-item label="员工">
          <el-select v-model="orderForm.employeeName" placeholder="请选择员工">
            <el-option v-for="emp in employeeStore.employees" :key="emp.id" :label="emp.name" :value="emp.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-select v-model="orderForm.customerName" placeholder="请选择客户">
            <el-option v-for="cust in customerStore.customers" :key="cust.id" :label="cust.name" :value="cust.name" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="支付方式">
          <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式">
            <el-option label="现金" value="现金" />
            <el-option label="微信" value="微信" />
            <el-option label="支付宝" value="支付宝" />
          </el-select>
        </el-form-item>
        <el-form-item label="购买数量" required :error="orderQuantityError">
          <el-input-number v-model="orderForm.quantity" :min="1" :max="orderForm.maxStock" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showOrderModal = false">取消</el-button>
          <el-button type="primary" @click="handleOrderConfirm">确认下单</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 进货弹窗 -->
    <el-dialog v-model="showRestockModal" title="商品进货" width="40%">
      <el-form :model="restockForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="restockForm.productName" disabled />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="restockForm.brand" disabled />
        </el-form-item>
        <el-form-item label="供应商" required>
          <el-select v-model="restockForm.supplierId" placeholder="请选择供应商" style="width: 100%">
            <el-option v-for="sup in allSuppliers" :key="sup.id" :label="sup.name" :value="sup.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="进货数量" required>
          <el-input-number v-model="restockForm.quantity" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="进货单价(¥)" required>
          <el-input-number v-model="restockForm.unitPrice" :precision="2" :min="0.01" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRestockModal = false">取消</el-button>
          <el-button type="primary" @click="handleRestockConfirm">确认进货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import request from '../utils/request'
import { useOrderStore } from '../stores/orderStore'
import { useEmployeeStore } from '../stores/employeeStore'
import { useCustomerStore } from '../stores/customerStore'
import { useMemberStore } from '../stores/memberStore'
import { useConsumptionStore } from '../stores/consumptionStore'
import { useProductOrderStore } from '../stores/productOrderStore'

// 响应式数据
const activeTab = ref('products')
const showAddModal = ref(false)
const showAddPurchaseModal = ref(false)
const editingProduct = ref(null)
const editingPurchase = ref(null)

// 商品数据
const products = ref([])

// 进货记录数据
const purchaseRecords = ref([])
const purchaseTotal = ref(0)

// 搜索表单
const searchForm = ref({
  productName: '',
  category: '',
  brand: '',
  minStock: '',
  maxStock: ''
})

const purchaseSearchForm = ref({
  startDate: '',
  endDate: '',
})

// 商品表单
const productForm = reactive({
  name: '',
  category: '',
  brand: '',
  specification: '',
  purchasePrice: 0,
  salePrice: 0,
  stock: 0,
  expiryDate: '',
  image: ''
})

// 进货表单
const purchaseForm = reactive({
  supplierName: '',
  supplierContact: '',
  purchaseDate: '',
  productName: '',
  quantity: 1,
  unitPrice: 0
})

// 分页相关变量
const productCurrentPage = ref(1)
const productPageSize = ref(10)
const productTotal = ref(0)
const purchaseCurrentPage = ref(1)
const purchasePageSize = ref(10)

const mapProductFields = (item) => ({
  id: item.id,
  name: item.name,
  category: item.category,
  brand: item.brand,
  specification: item.spec || item.specification || '',
  purchasePrice: Number(item.purchasePrice ?? item.purchase_price ?? 0),
  salePrice: Number(item.salePrice ?? item.sale_price ?? 0),
  stock: item.stock,
  expiryDate: item.expiryDate
    ? (typeof item.expiryDate === 'string' || typeof item.expiryDate === 'number'
        ? (dayjs(item.expiryDate).isValid() ? dayjs(item.expiryDate).format('YYYY-MM-DD') : String(item.expiryDate))
        : '')
    : (item.expiry_date
        ? (typeof item.expiry_date === 'string' || typeof item.expiry_date === 'number'
            ? (dayjs(item.expiry_date).isValid() ? dayjs(item.expiry_date).format('YYYY-MM-DD') : String(item.expiry_date))
            : '')
        : ''),
  //supplier: item.supplier || '',
});

const loadProducts = async () => {
  try {
    const params = {
      ...searchForm.value,
      pageNum: productCurrentPage.value,
      pageSize: productPageSize.value
    }
    const response = await request.post('/employee-pet/product/list', params)
    let arr = []
    if (response.data && Array.isArray(response.data.data)) {
      arr = response.data.data
      productTotal.value = response.data.total || 0
    }
    products.value = arr.map(mapProductFields)
    if (arr.length === 0) {
      ElMessage.info('暂无商品数据')
    }
  } catch (error) {
    products.value = []
    productTotal.value = 0
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

const handleProductPageChange = (page) => {
  productCurrentPage.value = page
  loadProducts()
}
const handleProductSizeChange = (size) => {
  productPageSize.value = size
  productCurrentPage.value = 1
  loadProducts()
}

// 计算属性：过滤后的商品列表
const filteredProducts = computed(() => {
  return products.value.filter(product => {
    const matchName = !searchForm.value.productName ||
      product.name.includes(searchForm.value.productName)
    const matchCategory = !searchForm.value.category ||
      product.category === searchForm.value.category
    const matchBrand = !searchForm.value.brand ||
      product.brand.includes(searchForm.value.brand)
    const matchMinStock = !searchForm.value.minStock ||
      product.stock >= parseInt(searchForm.value.minStock)
    const matchMaxStock = !searchForm.value.maxStock ||
      product.stock <= parseInt(searchForm.value.maxStock)

    return matchName && matchCategory && matchBrand && matchMinStock && matchMaxStock
  })
})

// 低库存商品数量
const lowStockCount = computed(() => {
  // 用 allProducts 统计全量低库存
  return allProducts.value.filter(products => products.stock < 20).length
})

// 计算属性：过滤后的进货记录
const filteredPurchaseRecords = computed(() => {
  return purchaseRecords.value.filter(record => {
    const matchStartDate = !purchaseSearchForm.value.startDate ||
      record.purchaseDate >= purchaseSearchForm.value.startDate
    const matchEndDate = !purchaseSearchForm.value.endDate ||
      record.purchaseDate <= purchaseSearchForm.value.endDate

    return matchStartDate && matchEndDate
  })
})

// 进货分页后的数据
const pagedPurchaseRecords = computed(() => {
  const start = (purchaseCurrentPage.value - 1) * purchasePageSize.value
  const end = start + purchasePageSize.value
  return filteredPurchaseRecords.value.slice(start, end)
})

// 方法
const getStockTagType = (stock) => {
  if (stock < 20) return 'danger'
  if (stock < 50) return 'warning'
  return 'success'
}

const handleSearch = () => {
  productCurrentPage.value = 1
  loadProducts()
}

const handleReset = () => {
  searchForm.value = {
    productName: '',
    category: '',
    brand: '',
    minStock: '',
    maxStock: ''
  }
  loadProducts()
  ElMessage.info('已重置搜索条件')
}

const handleEdit = (product) => {
  editingProduct.value = product
  Object.assign(productForm, product)
  showAddModal.value = true
}

const handleDelete = async (product) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个商品吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    try {
      const response = await request.post('/employee-pet/product/delete', {
        id: product.id
      })

      if (response.code === 200) {
        ElMessage.success('删除成功')
        // 重新加载商品列表
        await loadProducts()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleEditPurchase = (purchase) => {
  editingPurchase.value = purchase
  Object.assign(purchaseForm, purchase)
  showAddPurchaseModal.value = true
}

const handleDeletePurchase = async (purchase) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条进货记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const index = purchaseRecords.value.findIndex(item => item.id === purchase.id)
    if (index > -1) {
      purchaseRecords.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleImageChange = (file) => {
  console.log('选择图片:', file)
}

const handleSaveProduct = async () => {
  // 简单的前端验证
  if (!productForm.name) {
    ElMessage.error('商品名称不能为空')
    return
  }
  if (!productForm.category) {
    ElMessage.error('商品分类不能为空')
    return
  }
  if (productForm.purchasePrice <= 0) {
    ElMessage.error('进货价必须大于0')
    return
  }
  if (productForm.salePrice <= 0) {
    ElMessage.error('销售价必须大于0')
    return
  }
  if (productForm.stock < 0) {
    ElMessage.error('库存不能为负数')
    return
  }

  try {
    // 新增商品时，库存字段不传给后端
    const productData = {
      ...productForm,
      stock: 0, // 新增商品时库存为0
      expiryDate: formatDate(productForm.expiryDate)
    }
    let response
    if (editingProduct.value) {
      // 编辑
      response = await request.post('/employee-pet/product/update', {
        ...productData,
        id: editingProduct.value.id
      })
    } else {
      // 新增
      response = await request.post('/employee-pet/product/add', productData)
      // 新增成功后自动生成进货记录
      if (response.code === 200 && response.data && response.data.id) {
        const purchaseParams = {
          supplierId: productForm.supplierId,
          purchaseDate: dayjs().format('YYYY-MM-DD'),
          productId: response.data.id,
          quantity: productForm.stock, // 这里才用用户输入的库存
          unitPrice: productForm.purchasePrice
        }
        //await request.post('/employee-pet/product/purchase/add', purchaseParams)
        await loadPurchaseRecords()
      }
    }

    if (response.code === 200) {
      ElMessage.success(editingProduct.value ? '商品信息更新成功' : '商品添加成功')
      await loadProducts()
    } else {
      ElMessage.error(response.message || (editingProduct.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('保存商品失败:', error)
    ElMessage.error('保存商品失败')
  }

  showAddModal.value = false
  editingProduct.value = null
  Object.assign(productForm, {
    name: '',
    category: '',
    brand: '',
    specification: '',
    purchasePrice: 0,
    salePrice: 0,
    stock: 0,
    expiryDate: '',
    image: ''
  })
}

const handleSavePurchase = () => {
  if (editingPurchase.value) {
    // 编辑进货记录
    const index = purchaseRecords.value.findIndex(item => item.id === editingPurchase.value.id)
    if (index > -1) {
      purchaseRecords.value[index] = {
        ...editingPurchase.value,
        ...purchaseForm,
        purchaseDate: formatDate(purchaseForm.purchaseDate),
        totalAmount: purchaseForm.quantity * purchaseForm.unitPrice
      }
    }
    ElMessage.success('进货记录更新成功')
  } else {
    // 新增进货记录
    const newPurchase = {
      id: 'PR' + Date.now(),
      ...purchaseForm,
      purchaseDate: formatDate(purchaseForm.purchaseDate),
      totalAmount: purchaseForm.quantity * purchaseForm.unitPrice
    }
    purchaseRecords.value.push(newPurchase)
    ElMessage.success('进货记录添加成功')
  }

  showAddPurchaseModal.value = false
  editingPurchase.value = null
  Object.assign(purchaseForm, {
    supplierName: '',
    supplierContact: '',
    purchaseDate: '',
    productName: '',
    quantity: 1,
    unitPrice: 0
  })
}

// 保质期格式化函数
const formatDate = (date) => {
  if (!date) return ''
  // 兼容Date对象、字符串、时间戳
  return dayjs(date).isValid() ? dayjs(date).format('YYYY-MM-DD') : date
}

const phoneRules = [
  { required: true, message: '请输入手机号', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
];
const emailRules = [
  { required: true, message: '请输入邮箱', trigger: 'blur' },
  { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
];

// 供应商管理相关数据
const showAddSupplierModal = ref(false)
const editingSupplier = ref(null)
const suppliers = ref([])
const supplierForm = reactive({
  id: null,
  name: '',
  contact: '',
  address: ''
})
const supplierSearchForm = ref({
  supplierName: '',
  contact: '',
  address: ''
})
const supplierCurrentPage = ref(1)
const supplierPageSize = ref(10)
const supplierTotal = ref(0)

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    const response = await request.post('/employee-pet/product/supplier/list', {
      ...supplierSearchForm.value,
      pageNum: supplierCurrentPage.value,
      pageSize: supplierPageSize.value
    })

    // 兼容不同返回结构
    let supplierList = []
    let total = 0

    if (response.data && Array.isArray(response.data.data)) {
      supplierList = response.data.data
      productTotal.value = response.data.total
      total = response.data.total
    }
    suppliers.value = supplierList
    supplierTotal.value = total
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    suppliers.value = []
    supplierTotal.value = 0
  }
}

// 供应商分页处理
const handleSupplierPageChange = (page) => {
  supplierCurrentPage.value = page
  loadSuppliers()
}

const handleSupplierSizeChange = (size) => {
  supplierPageSize.value = size
  supplierCurrentPage.value = 1
  loadSuppliers()
}
// 方法
const handleSupplierSearch = () => {
  supplierCurrentPage.value = 1
  loadSuppliers()
  ElMessage.success('搜索完成')
}

const handleSupplierReset = () => {
  supplierSearchForm.value = { supplierName: '', contact: '', address: '' }
  supplierCurrentPage.value = 1
  loadSuppliers()
  ElMessage.info('已重置搜索条件')
}

const handleEditSupplier = (supplier) => {
  editingSupplier.value = supplier
  Object.assign(supplierForm, {
    id: supplier.id,
    name: supplier.name,
    contact: supplier.contact,
    address: supplier.address
  })
  showAddSupplierModal.value = true
}

const handleDeleteSupplier = async (supplier) => {
  try {
    await ElMessageBox.confirm('确定要删除该供应商吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    try {
      const response = await request.post('/employee-pet/product/supplier/delete', {
        id: supplier.id
      })

      if (response.code === 200) {
        ElMessage.success('删除成功')
        // 重新加载供应商列表
        await loadSuppliers()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除供应商失败:', error)
      ElMessage.error('删除供应商失败')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleSaveSupplier = async () => {
  // 验证必填字段
  if (!supplierForm.name) {
    ElMessage.error('供应商名称不能为空')
    return
  }
  if (!supplierForm.contact) {
    ElMessage.error('联系方式不能为空')
    return
  }
  if (!supplierForm.address) {
    ElMessage.error('地址不能为空')
    return
  }

  try {
    let response
    if (editingSupplier.value) {
      // 编辑
      response = await request.post('/employee-pet/product/supplier/update', {
        id: supplierForm.id,
        name: supplierForm.name,
        contact: supplierForm.contact,
        address: supplierForm.address
      })
    } else {
      // 新增
      response = await request.post('/employee-pet/product/supplier/add', {
        name: supplierForm.name,
        contact: supplierForm.contact,
        address: supplierForm.address
      })
    }

    if (response.code === 200) {
      ElMessage.success(editingSupplier.value ? '供应商信息更新成功' : '供应商添加成功')
      // 重新加载供应商列表
      await loadSuppliers()
    } else {
      ElMessage.error(response.message || (editingSupplier.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('保存供应商失败:', error)
    ElMessage.error('保存供应商失败')
  }

  showAddSupplierModal.value = false
  editingSupplier.value = null
  Object.assign(supplierForm, { id: null, name: '', contact: '', address: '' })
}

// 下单相关
const showOrderModal = ref(false)
const orderStore = useOrderStore()
const employeeStore = useEmployeeStore()
const customerStore = useCustomerStore()
const memberStore = useMemberStore()
const consumptionStore = useConsumptionStore()
const productOrderStore = useProductOrderStore()
const orderForm = reactive({
  productId: '',
  productName: '',
  brand: '',
  salePrice: 0,
  employeeName: '',
  customerName: '',
  paymentMethod: '',
  quantity: 1,
  maxStock: 0
})
const orderEmployeeError = ref('')
const orderQuantityError = ref('')
const openOrderModal = (product) => {
  orderForm.productId = product.id
  orderForm.productName = product.name
  orderForm.brand = product.brand
  orderForm.salePrice = product.salePrice
  orderForm.employeeName = ''
  orderForm.customerName = ''
  orderForm.quantity = 1
  orderForm.maxStock = product.stock
  orderEmployeeError.value = ''
  orderQuantityError.value = ''
  showOrderModal.value = true
}
const handleOrderConfirm = async () => {
  if (!orderForm.employeeName) {
    orderEmployeeError.value = '请选择员工'
    return
  }
  orderEmployeeError.value = ''
  if (!orderForm.customerName) {
    ElMessage.error('请选择客户')
    return
  }
  if (!orderForm.paymentMethod) {
    ElMessage.error('请选择支付方式')
    return
  }
  if (orderForm.quantity < 1 || orderForm.quantity > orderForm.maxStock) {
    orderQuantityError.value = '购买数量不能大于库存且不少于1'
    return
  }

  try {
    console.log('下单参数', {
      productId: orderForm.productId,
      productName: orderForm.productName,
      brand: orderForm.brand,
      salePrice: orderForm.salePrice,
      employeeName: orderForm.employeeName,
      customerName: orderForm.customerName,
      paymentMethod: orderForm.paymentMethod,
      quantity: orderForm.quantity
    })

    const customer = customerStore.customers.find(c => c.name === orderForm.customerName)
    const employee = employeeStore.employees.find(e => e.name === orderForm.employeeName)
    const orderParams = {
      productId: orderForm.productId,
      employeeId: employee?.id,
      customerId: customer?.id,
      paymentMethod: orderForm.paymentMethod,
      quantity: orderForm.quantity,
      totalAmount: orderForm.salePrice * orderForm.quantity,
      orderType: '商品销售',
      createdAt: new Date(),
    }
    const res = await productOrderStore.addOrder(orderParams)
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('下单成功')
      showOrderModal.value = false
      await loadAllProducts()
      await loadProducts()
      await loadPurchaseRecords()

      // 判断是否会员并积分（统一用customerStore）
      let addPoints = 0
      if (customer && customer.isMember) {
        let rate = 1
        if (customer.memberLevel === '金卡会员') rate = 1.5
        else if (customer.memberLevel === '银卡会员') rate = 1.2
        addPoints = Math.floor(orderForm.salePrice * orderForm.quantity * rate)
        await customerStore.updateCustomer(customer.id, {
          pointsBalance: customer.pointsBalance + addPoints,
          lastConsumptionDate: dayjs().format('YYYY-MM-DD')
        })
        // 消费记录写入consumptionStore
        consumptionStore.addRecord({
          memberNumber: customer.memberNumber,
          type: '消费',
          amount: orderForm.salePrice * orderForm.quantity,
          points: addPoints,
          description: `购买商品：${orderForm.productName}`,
          date: dayjs().format('YYYY-MM-DD')
        })
      }
    } else {
      ElMessage.error(res.message || '下单失败')
    }
  } catch (error) {
    console.error('下单失败:', error)
    ElMessage.error('下单失败')
  }
}
// 进货相关
const showRestockModal = ref(false)
const restockForm = reactive({
  productId: '',
  productName: '',
  brand: '',
  supplierId: '',
  quantity: 1,
  unitPrice: 0
})
const openRestockModal = (product) => {
  restockForm.productId = product.id
  restockForm.productName = product.name
  restockForm.brand = product.brand
  restockForm.supplierId = ''
  restockForm.quantity = 1
  restockForm.unitPrice = product.purchasePrice
  showRestockModal.value = true
}
const handleRestockConfirm = async () => {
  if (!restockForm.supplierId) {
    ElMessage.error('请选择供应商')
    return
  }
  if (restockForm.quantity < 1) {
    ElMessage.error('进货数量需大于0')
    return
  }
  if (restockForm.unitPrice <= 0) {
    ElMessage.error('进货单价需大于0')
    return
  }
  try {
    const params = {
      supplierId: restockForm.supplierId,
      purchaseDate: dayjs().format('YYYY-MM-DD'),
      productId: restockForm.productId,
      quantity: restockForm.quantity,
      unitPrice: restockForm.unitPrice
    }
    const response = await request.post('/employee-pet/product/purchase/add', params)
    if (response.code === 200) {
      ElMessage.success('进货成功')
      showRestockModal.value = false
      await loadAllProducts()
      await loadProducts()
      await loadPurchaseRecords()

    } else {
      ElMessage.error(response.message || '进货失败')
    }
  } catch (error) {
    ElMessage.error('进货失败')
  }
}

// 新增方法：根据供应商名获取商品名
const getSupplierProducts = (supplierName) => {
  return products.value
    .filter(p => p.supplier === supplierName)
    .map(p => p.name)
    .join('，') || '-';
}

// 监听供应商选择，自动填充联系方式
watch(() => purchaseForm.supplierName, (newSupplierName) => {
  if (newSupplierName) {
    const selectedSupplier = suppliers.value.find(sup => sup.name === newSupplierName)
    if (selectedSupplier) {
      purchaseForm.supplierContact = selectedSupplier.contact
    }
  } else {
    purchaseForm.supplierContact = ''
  }
})

const allProducts = ref([])
const allSuppliers = ref([])

const loadAllProducts = async () => {
  try {
    const response = await request.post('/employee-pet/product/list', {
      pageNum: 1,
      pageSize: 10000
    })
    if (response.data && Array.isArray(response.data.data)) {
      allProducts.value = response.data.data
      productTotal.value = response.data.total
    }
    console.log('allProducts', allProducts.value)
  } catch (e) {
    allProducts.value = []
  }
}

const loadAllSuppliers = async () => {
  try {
    const response = await request.post('/employee-pet/product/supplier/list', {
      pageNum: 1,
      pageSize: 10000
    })
    if (response.data && Array.isArray(response.data.data)) {
      allSuppliers.value = response.data.data
      supplierTotal.value = response.data.total
    }
    console.log('allSuppliers', allSuppliers.value)
  } catch (e) {
    allSuppliers.value = []
  }
}

const mapPurchaseFields = (item) => {
  const supplier = allSuppliers.value.find(s => String(s.id) === String(item.supplierId))
  const product = allProducts.value.find(p => String(p.id) === String(item.productId))
  return {
    ...item,
    supplierName: supplier ? supplier.name : item.supplierId,
    supplierContact: supplier ? supplier.contact : '',
    productName: product ? product.name : item.productId,
    purchaseDate: formatDate(item.purchaseDate),
    unitPrice: Number(item.unitPrice),
    totalAmount: Number(item.totalAmount)
  }
}

const loadPurchaseRecords = async () => {
  try {
    const params = {
      ...purchaseSearchForm.value,
      pageNum: purchaseCurrentPage.value,
      pageSize: purchasePageSize.value
    }
    if (params.startDate instanceof Date) params.startDate = formatDate(params.startDate)
    if (params.endDate instanceof Date) params.endDate = formatDate(params.endDate)
    if (!params.startDate) delete params.startDate
    if (!params.endDate) delete params.endDate

    const response = await request.post('/employee-pet/product/purchase/list', params)
    let arr = []
    if (response.data && response.data.data && Array.isArray(response.data.data)) {
      arr = response.data.data
      purchaseTotal.value = response.data.total || 0
    }
    console.log('purchaseRecords原始数据', arr)
    purchaseRecords.value = arr.map(mapPurchaseFields)
  } catch (error) {
    purchaseRecords.value = []
    purchaseTotal.value = 0
    ElMessage.error('获取进货记录失败')
  }
}

const handlePurchasePageChange = (page) => {
  purchaseCurrentPage.value = page
  loadPurchaseRecords()
}
const handlePurchaseSizeChange = (size) => {
  purchasePageSize.value = size
  purchaseCurrentPage.value = 1
  loadPurchaseRecords()
}
const handlePurchaseSearch = () => {
  purchaseCurrentPage.value = 1
  loadPurchaseRecords()
}

const handlePurchaseReset = () => {
  purchaseSearchForm.value.startDate = ''
  purchaseSearchForm.value.endDate = ''
  purchaseCurrentPage.value = 1
  loadPurchaseRecords()
}

onMounted(async () => {
  await loadAllProducts()
  await loadAllSuppliers()
  await loadProducts()
  await loadSuppliers()
  await loadPurchaseRecords()
  employeeStore.fetchEmployees(1, 9999)
  await customerStore.fetchCustomers()
})
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}

.inventory-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.tab-content {
  margin-top: 20px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tab-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.stock-alert {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
